<?php

/**
 * User: hitman
 * Date: 17/10/2017
 * Time: 10:53 AM
 */

namespace Hitman\Slagger\Commands;
use Illuminate\Support\Facades\DB;

trait CommandTrait
{
    /**
     * 获取配置
     */
    public function getSlaggerConfig()
    {
        $file = config('slagger.file');
        if (file_exists($file)) {
            $config = json_decode(file_get_contents($file), true);
        } else {
            $config = config('slagger.default');
        }

        return $config;
    }

    public function writeSlaggerConfig($config)
    {
        file_put_contents(config('slagger.file'), json_encode($config, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
    }

    /**
     * 获取数据表字段
     * @param $table
     * @return array
     */
    public function getFields($table)
    {
        $meta = DB::select("show full fields from $table");
        $fields = collect($meta)->map(function($m){
            return [
                'field' => $m->Field,
                'type' => $m->Type,
                'comment' => $m->Comment,
            ];
        })->toArray();

        return $fields;
    }

    /**
     * 获取项目Model
     * @return array
     */
    public function getModels()
    {
        $modelPath = app_path('Models');
        $modelFiles = scandir($modelPath);

        $models = collect($modelFiles)->filter(function($f){
            return $f != '.' && $f != '..' && $f != 'Model.php';
        })->map(function($f) {
            return str_replace(".php", "", $f);
        })->toArray();

        return $models;
    }

    /**
     * 获取项目数据表
     * @return mixed
     */
    public function getTables()
    {
        $models = $this->getModels();

        return $models->map(function($model){
            $namespaceModel = "App\\Models\\";
            $m = new $namespaceModel;

            return $m->getTable();
        });
    }

    /**
     * 获取 [ Model => [ Fields ] ] 对应关系
     * @return array
     */
    public function getModelMap()
    {
        $models = $this->getModels();

        return collect($models)->flatMap(function($model){
            $namespaceModel = "App\\Models\\" . $model;
            $m = new $namespaceModel;
            $table = $m->getTable();
            $fields = $this->getFields($table);

            return [$model => $fields];
        })->toArray();
    }

    /**
     * 获取 path 模板
     * @param $resource
     * @return mixed
     */
    public function getPathTemplate($resource)
    {
        $template         = config('slagger.template.path');
        $template['tags'] = [$resource];

        return $template;
    }
}